﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HelperPrototype.OtherForms
{
    public partial class ThemSuaNhomHangHoaForm : Form
    {
        private int ID = -1;

        public ThemSuaNhomHangHoaForm()
        {
            InitializeComponent();
        }

        public ThemSuaNhomHangHoaForm(int groupItemID)
        {
            InitializeComponent();
            this.Text = "Chỉnh sửa thông tin nhóm hàng hóa";
            ID = groupItemID;
            loadData();
        }

        private void loadData()
        {
            _DB.DataClasses1DataContext dc = new _DB.DataClasses1DataContext();
            _DB.NhomHangHoa ig = (from NhomHangHoa in dc.NhomHangHoas
                                where NhomHangHoa.NhomHangHoa_ID == ID
                                select NhomHangHoa).Single();

            txtName.Text = ig.TenNhomHangHoa;
            txtNote.Text = ig.GhiChu;
            txtStatus.Text = ig.TrangThai;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtName.Text.Equals(""))
            {
                MessageBox.Show("Name is empty!");
                return;
            }

            try
            {
                _DB.DataClasses1DataContext dc = new _DB.DataClasses1DataContext();
                _DB.NhomHangHoa ig;

                if (ID >= 0)
                {
                    ig = (from NhomHangHoa in dc.NhomHangHoas
                          where NhomHangHoa.NhomHangHoa_ID == ID
                          select NhomHangHoa).Single();
                } else
                {
                    ig = new _DB.NhomHangHoa();
                }
                
                ig.TenNhomHangHoa = txtName.Text;
                ig.TrangThai = txtStatus.Text;
                ig.GhiChu = txtNote.Text;

                if (ID < 0)
                    dc.NhomHangHoas.InsertOnSubmit(ig);

                dc.SubmitChanges();
                
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (ID >= 0)
                loadData();
            else
            {
                txtName.Text = "";
                txtNote.Text = "";
                txtStatus.Text = "";
            }
        }
    }
}
